package com.aaa.aspect;
/**
 * @create by: 玙德（3084385240@qq.com）
 * @description:
 * @create time: 2022/7/8 9:50
 * @param null
 * @return 
 */


import cn.hutool.core.util.ObjectUtil;
import com.aaa.entity.Log;
import com.aaa.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@Component
@Aspect
@EnableAspectJAutoProxy
public class LogAspect {

    @Autowired
    private LogService logService;

    @Autowired
    HttpSession httpSession;

    @Pointcut("execution(public * com.aaa.controller.*.*(..))")
    public void controller(){
    }

    /**
    * @Author: WTH
    * @Description: 日志打印
    * @Date:2022-07-07 08:39
    * @Params: 
    */
    @Around("controller()")
    public Object myLog(ProceedingJoinPoint joinPoint) throws UnknownHostException {
//        System.out.println("进入环绕通知");
        //获取方法参数
        Object[] args=joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        Log log=new Log();

        //获取用户名
        if(ObjectUtil.isNotEmpty(httpSession.getAttribute("userinfo"))){
            Map<String,Object> usermap= (Map<String, Object>) httpSession.getAttribute("userinfo");
            String username= (String) usermap.get("username");
            log.setLogin_name(username);
            log.setUser_name(username);
        }

        //获取请求的ip地址
        InetAddress addr=InetAddress.getLocalHost();
        log.setIp(addr.getHostAddress());

        //获取类名
        String className=joinPoint.getTarget().getClass().getName();
        log.setClass_name(className);

        //获取方法名
        String[] split=signature.toString().split("\\.");
        String methodName=split[split.length-1];
        log.setMethod_name(methodName);

        //获取参数
        String param= Arrays.toString(args);
        log.setParams(param);
        if(param.getBytes().length > 8889){
            log.setParams("Too long Params");
        }

        //获取时间
        log.setCreate_time(new Date());


        logService.addLog(log);

        try {
            Object priceed=joinPoint.proceed(args);
            return priceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}
